﻿using System.Security.AccessControl;
using Marbles.Core.Connectors;
using System;
using Marbles.Core;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Globalization;
using System.Data;
using Marbles.Core.Content.Templates;
using Marbles.Core.Content.Analytics;

namespace Marbles.Web.Admin.Content
{
    public partial class SiteMgr : ContentBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            cBtnNew.Visible = Page.AuthenticationProvider.CurrentToken.IsRoot;
            cPlRoot1.Visible = cBtnNew.Visible;
            cPlRoot2.Visible = cBtnNew.Visible;

            if ((!Page.IsPostBack) || (cDrpTheme.Items.Count == 0) || (cDrpLanguage.Items.Count == 0))
            {
                InitialiseForm();
            }

            LoadData();
        }

        private void LoadWebMaster(string siteid)
        {
            DataConnection dbc = new DataConnection();
            Command cmd = new Command("SELECT DISTINCT a.username, a.fullname FROM Users a INNER JOIN usergrouplink b ON a.userid = b.userid INNER JOIN usergroups c ON b.groupid = c.groupid WHERE c.editor = 1 OR c.administrator = 1 AND a.siteid = @siteid ORDER BY fullname ASC");
            cmd.AddParameter("@siteid", siteid);

            cDrpWebMaster.Items.Clear();
            cDrpWebMaster.Items.Add(new ListItem("", ""));
            foreach (DataRow dr in dbc.FetchDataTable(cmd).Rows)
            {
                cDrpWebMaster.Items.Add(new ListItem(dr["fullname"].ToString(), dr["username"].ToString()));
            }
        }

        private void InitialiseForm()
        {
            string path = HttpContext.Current.Server.MapPath("/App_Themes/");

            cDrpAnalytics.Items.Clear();
            cDrpAnalytics.DataSource = AnalyticsEngine.GetInstalledEngines();
            cDrpAnalytics.DataBind();
            cDrpAnalytics.Items.Insert(0, new ListItem("", ""));
            cDrpTheme.Items.Clear();
            cDrpTheme.Items.Add(new ListItem("", ""));
            foreach (string s in System.IO.Directory.GetDirectories(path))
            {
                DirectoryInfo info = new DirectoryInfo(s);
                if (info.Name.ToLower() == "admin") { continue; }
                cDrpTheme.Items.Add(new ListItem(info.Name, info.Name));
            }

            cDrpLanguage.Items.Clear();
            cDrpLanguage.Items.Add(new ListItem("", ""));
            SortedDictionary<string, string> items = new SortedDictionary<string, string>();
            string lang = "en";

            if (Request.UserLanguages.Length > 0)
            {
                string[] args = Request.UserLanguages[0].Split('-');
                if (args.Length == 2) { lang = args[0]; }
            }

            foreach (System.Globalization.CultureInfo culture in System.Globalization.CultureInfo.GetCultures(CultureTypes.NeutralCultures))
            {
                items.Add(culture.EnglishName, culture.TwoLetterISOLanguageName);
            }

            foreach (string s in items.Keys)
            {
                ListItem item = new ListItem(s, items[s]);
                if (item.Value == lang) { item.Selected = true; }
                cDrpLanguage.Items.Add(item);
            }

        }

        private void EditSite()
        {
            Clear();
            Core.Content.Sites.SiteDefinition web = Core.Content.Sites.SiteDefinition.GetCurrent();
            __SITE.Value = web.SiteId.ToString();
            cTxtCopyright.Text = web.CopyRight;
            LoadWebMaster(web.SiteId);
            cDrpWebMaster.SelectedValue = web.WebMaster;
            cTxtSiteName.Text = web.SiteName;
            cTxtRobots.Text = web.Robots;
            cTxtResourceDirectory.Text = web.ResourceDirectory1;
            cTxtHost.Text = web.Host;
            cTxtExpiryHours.Text = web.ExpiryHours.ToString();
            cDrpLanguage.SelectedValue = web.Language;
            cTxtTitle.Text = web.Title;
            cDrpTheme.ClearSelection();
            
            foreach (ListItem item in cDrpTheme.Items)
            {
                if (item.Value == web.Theme) { item.Selected = true; break; }
            }

            cBtnNew.Enabled = false;
            cBtnSave.Enabled = true;
            cBtnCancel.Enabled = true;
            cChkAllowComments.Enabled = true;
            cChkAllowComments.Checked = web.AllowComments;
            cBtnSave.CommandArgument = web.SiteId.ToString();
            cDrpAnalytics.SelectedValue = web.AnalyticsEngine;
            cTxtAnalyticsUid.Text = web.GetWebAnalyticsSettings("ACCOUNT");
            cBtnSave.CommandName = "Save";
            SetState(true);

        }

        private void LoadData()
        {

            if ((!cBtnNew.Visible) && (string.IsNullOrEmpty(__SITE.Value)))
            {
                EditSite();
            }
            else
            {
                DataConnection dbc = new DataConnection();
                Command cmd = new Command("SELECT sitename, siteid, host, title FROM sites ORDER BY title ASC");
                DataTable dt = dbc.FetchDataTable(cmd);
                cLstSites.DataSource = dt;
                cLstSites.DataBind();
            }
        }

        private void Clear()
        {
            cBtnSave.CommandArgument = "0";
            cBtnSave.CommandName = "Insert";
            cBtnNew.Enabled = true;
            cDrpWebMaster.ClearSelection();
            cDrpTheme.ClearSelection();
            cDrpTheme.ClearSelection();
            cTxtCopyright.Text = "";
            cBtnSave.Enabled = false;
            cBtnCancel.Enabled = false;
            cDrpLanguage.ClearSelection();
            cDrpTheme.ClearSelection();
            cTxtExpiryHours.Text = "";
            cChkAllowComments.Checked = false;
            cTxtHost.Text = "";
            cTxtResourceDirectory.Text = "";
            cTxtRobots.Text = "";
            cTxtTitle.Text = "";
            cDrpAnalytics.ClearSelection();
            cTxtAnalyticsUid.Text = "";
            cTxtSiteName.Text = "";
            __SITE.Value = "";
            SetState(false);
        }

        private void SetState(bool enabled)
        {
            cDrpAnalytics.Enabled = enabled;
            cTxtAnalyticsUid.Enabled = enabled;
            cChkAllowComments.Enabled = enabled;
            cDrpWebMaster.Enabled = enabled;
            cTxtCopyright.Enabled = enabled;
            cDrpLanguage.Enabled = enabled;
            cDrpTheme.Enabled = enabled;
            cTxtExpiryHours.Enabled = enabled;
            cTxtHost.Enabled = enabled;
            cTxtResourceDirectory.Enabled = enabled;
            cTxtRobots.Enabled = enabled;
            cTxtSiteName.Enabled = enabled;
            cTxtTitle.Enabled = enabled;
        }

        protected void Page_Command(object sender, CommandEventArgs e)
        {
            Core.Content.Sites.SiteDefinition web = null;

            switch (e.CommandName)
            {
                case "Edit":
                    web = Core.Content.Sites.SiteDefinition.GetSiteBySiteId(e.CommandArgument.ToString());
                    __SITE.Value = web.SiteId.ToString();
                    LoadWebMaster(web.SiteId);
                    cTxtCopyright.Text = web.CopyRight;
                    cTxtSiteName.Text = web.SiteName;
                    cTxtRobots.Text = web.Robots;
                    cTxtResourceDirectory.Text = web.ResourceDirectory1;
                    cTxtHost.Text = web.Host;
                    cTxtExpiryHours.Text = web.ExpiryHours.ToString();
                    cDrpWebMaster.SelectedValue = web.WebMaster;
                    cDrpLanguage.SelectedValue = web.Language;
                    cChkAllowComments.Checked = web.AllowComments;
                    cTxtTitle.Text = web.Title;
                    cDrpTheme.SelectedValue = web.Theme;
                    cDrpAnalytics.SelectedValue = web.AnalyticsEngine;
                    cTxtAnalyticsUid.Text = web.GetWebAnalyticsSettings("ACCOUNT");
                    cBtnNew.Enabled = false;
                    cBtnSave.Enabled = true;
                    cBtnCancel.Enabled = true;
                    cBtnSave.CommandArgument = e.CommandArgument.ToString();
                    cBtnSave.CommandName = "Save";
                    SetState(true);
                    break;
                case "New":
                    Clear();
                    cBtnSave.CommandArgument = "0";
                    cBtnSave.CommandName = "Insert";
                    cBtnNew.Enabled = false;
                    cBtnSave.Enabled = true;
                    cBtnCancel.Enabled = true;
                    __SITE.Value = "0";
                    SetState(true);
                    break;
                case "Save":
                    web = Core.Content.Sites.SiteDefinition.GetSiteBySiteId(e.CommandArgument.ToString());
                    web.SiteName = cTxtSiteName.Text;
                    web.Robots = cTxtRobots.Text;
                    web.ResourceDirectory1 = cTxtResourceDirectory.Text;
                    web.Host = cTxtHost.Text;
                    web.Language = cDrpLanguage.SelectedValue;
                    web.Theme = cDrpTheme.SelectedValue;
                    web.Title = cTxtTitle.Text;
                    web.AllowComments = cChkAllowComments.Checked;
                    web.CopyRight = cTxtCopyright.Text;
                    web.WebMaster = cDrpWebMaster.SelectedValue;
                    web.AnalyticsEngine = cDrpAnalytics.SelectedValue;
                    web.SetWebAnalyticsSettings("ACCOUNT", cTxtAnalyticsUid.Text);

                    if (string.IsNullOrEmpty(cTxtExpiryHours.Text)) { web.ExpiryHours = 0; }
                    else
                    {
                        web.ExpiryHours = Convert.ToInt32(cTxtExpiryHours.Text);
                    }

                    if (!Directory.Exists(web.ApplicationResourceDirectory))
                    {
                        Directory.CreateDirectory(web.ApplicationResourceDirectory);
                    }

                    if (!Directory.Exists(web.ApplicationTemplateDirectory))
                    {
                        Directory.CreateDirectory(web.ApplicationTemplateDirectory);
                    }

                    
                    web.Update();
                    Clear();
                    LoadData();
                    break;
                case "Insert":
                    web = Core.Content.Sites.SiteDefinition.CreateNew();
                    web.SiteName = cTxtSiteName.Text;
                    web.Robots = cTxtRobots.Text;
                    web.ResourceDirectory1 = cTxtResourceDirectory.Text;
                    web.Host = cTxtHost.Text;
                    web.Language = cDrpLanguage.SelectedValue;
                    web.Title = cTxtTitle.Text;
                    web.CopyRight = cTxtCopyright.Text;
                    web.WebMaster = cDrpWebMaster.SelectedValue;
                    web.Theme = cDrpTheme.SelectedValue;
                    web.AllowComments = cChkAllowComments.Checked;
                    web.AnalyticsEngine = cDrpAnalytics.SelectedValue;
                    web.SetWebAnalyticsSettings("ACCOUNT", cTxtAnalyticsUid.Text);

                    if (string.IsNullOrEmpty(cTxtExpiryHours.Text)) { web.ExpiryHours = 0; }
                    else
                    {
                        web.ExpiryHours = Convert.ToInt32(cTxtExpiryHours.Text);
                    }

                    web.Insert();
                    Marbles.Core.Authentication.AuthenticationProvider.CopyRootUser(CurrentWeb.SiteId, web.SiteId);
                    Clear();
                    LoadData();
                    break;
                case "Cancel":
                    Clear();
                    break;
            }
        }
    }
}